<template>
  <div id="taxi">
    <taxi-map
      :class="$route.name=='taxi'?'map100':'map'"
      :center="getCurrentLocation.coordinate"
      ref="map"
      @select="onMapSelect"
      @complete="onMapComplete"
      @dragstart="onMapDragStart"
    ></taxi-map>
    <taxibottom ref="bottom" @dingwei="dingweiBtn" @changeStartPosition="onChangeStartPosition" @changeEndPosition="onChangeEndPosition"></taxibottom>
  </div>
</template>

<script>
import TaxiMap from '@/components/map/TaxiMap';
import TaxiBottom from './TaxiBottom';
import { GET_CURRENT_LOCATION } from '@/store/actions.types';
import {
  TAXI_STATUS_ORDERING,
  TAXI_STATUS_STANDBY,
  TAXI_STATUS_PICKING,
  TAXI_STATUS_ARRIVED,
  TAXI_STATUS_TRAVELLING,
  TAXI_STATUS_FINISHED,
  TAXI_STATUS_CANCELD,
  TAXI_STATUS_CLOSED
} from './types';
import { mapGetters } from 'vuex';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import { Dialog } from 'mand-mobile';
import { GPS_UNKNOWN, GPS_LOCATING, GPS_SUCCESS, GPS_ERROR } from '@/store/gps.types';
export default {
  name: 'taxi',
  data() {
    return {
      status: 0,
      isListItem: false,
      mqttInited: false,
      orderTopicSubscribed: false,
      gpsTopicSubscribed: false,
      hasDrivePath: false,
      gettingLocation: true
    };
  },
  components: {
    [TaxiMap.name]: TaxiMap,
    [TaxiBottom.name]: TaxiBottom
  },
  methods: {
    init() {
      if (this.getTaxiBottomType === '0') {
        this.$refs.map.clearMap();
        this.$refs.map.initCenter();
        this.$refs.map.initPositionPicker();
        this.$refs.map.initCenter(this.getCurrentLocation.coordinate);
      } else if (this.getTaxiBottomType === '1') {
        this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition);
        this.$refs.map.stopPositionPicker();
      } else if (this.getTaxiBottomType === '3') {
        this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition, true);
        this.$refs.map.stopPositionPicker();
      }
      if (this.gpsStatus === GPS_ERROR) {
        Dialog.alert({
          title: '获取不到您的定位',
          content: '允许“平安到家”使用您的定位，以获取当前城市和准确的订单起点',
          confirmText: '我知道了'
        });
      }
      console.log('出租车初始化完毕');
    },
    onMapComplete() {
      this.init();
    },
    onMapDragStart() {
      this.isListItem = false;
      if (this.getTaxiBottomType === '0') {
        let position = this.taxiStartPosition;
        position.start_pst = '正在获取上车地点';
        this.$store.commit('setTaxiStartPosition', position);
      }
    },
    onMapSelect(poi) {
      if (this.isListItem) {
        return;
      }
      let position = {
        // 出租车起点信息
        start_pst: poi.stationName,
        start_pst_detail: poi.position,
        start_lnglat: poi.coordinate.join(','),
        start_code: poi.adcode
      };
      this.$store.commit('setTaxiStartPosition', position);
      this.gettingLocation = false;
      console.log('更换了上车点：', poi);
      this.$store.dispatch('getTaxiNearDrivers', position.start_lnglat);
    },
    dingweiBtn() {
      if (this.getTaxiBottomType === '0') {
        this.$store
          .dispatch(GET_CURRENT_LOCATION)
          .then(() => {
            // this.$refs.map.initCenter(this.getCurrentLocation.coordinate);
            this.$refs.map.setFitView();
          })
          .catch(reason => {
            Dialog.alert({
              title: '获取不到您的定位',
              content: '允许“平安到家”使用您的定位，以获取当前城市和准确的订单起点',
              confirmText: '我知道了'
            });
          });
      } else {
        if (this.$refs.map) {
          this.$refs.map.setFitView();
        }
      }
    },
    onChangeStartPosition(poi) {
      console.log('从列表选择的上车点：', poi);
      this.isListItem = true;
      let position = {
        // 出租车起点信息
        start_pst: poi.stationName,
        start_pst_detail: poi.position,
        start_lnglat: poi.coordinate,
        start_code: poi.adcode
      };
      this.$store.commit('setTaxiStartPosition', position);
      this.$store.dispatch('getTaxiNearDrivers', position.start_lnglat);
      this.$refs.map.setCenter(position.start_lnglat.split(','));
    },
    onChangeEndPosition(poi) {
      console.log('从列表选择的下车点：', poi);
      let position = {
        end_pst: poi.stationName,
        end_pst_detail: poi.position,
        end_lnglat: poi.coordinate,
        end_code: poi.adcode
      };
      this.$store.commit('setTaxiEndPosition', position);
      // this.$refs.map.stopPositionPicker();
      // this.$refs.bottom.taxiList();
    },
    initMqtt() {
      if (this.mqttClient) {
        if (this.mqttConnected) {
          return;
        }
      }
      this.$store
        .dispatch('getMqttConfig')
        .then(() => {
          // 获取MQTT配
          if (this.mqttConfig) {
            this.$store.dispatch('initMqttClient', this.mqttConfig).then(() => {
              // 链接MQTT
              this.mqttInited = true;
              this.mqttClient.onMessageArrived = this.onMessageArrive;
              this.mqttClient.onConnectionLost = this.onMqttLost;
              this.subscribeOrderTopic();
              this.subscribeGpsTopic();
            });
          }
        })
        .catch(reason => {
          console.error('无法获取MQTT配置');
        });
    },
    subscribeOrderTopic() {
      if (this.orderTopicSubscribed) {
        return;
      }
      if (this.mqttInited) {
        this.$store.dispatch('subscribe', this.getTaxiOrderTopic).then(() => {
          this.orderTopicSubscribed = true;
        });
      }
    },
    subscribeGpsTopic() {
      if (this.gpsTopicSubscribed) {
        return;
      }
      if (this.mqttInited) {
        this.$store.dispatch('subscribe', this.getTaxiGpsTopic).then(() => {
          this.gpsTopicSubscribed = true;
        });
      }
    },
    initDrivePath(start, end) {
      return new Promise((resolve, reject) => {
        if (this.hasDrivePath) {
          reject(new Error('DrivePath has been inited'));
        }
        if (this.$refs.map && this.currentGpsPosition !== '') {
          this.$refs.map
            .createPathNavigator(start, end)
            .then(() => {
              this.hasDrivePath = true;
              this.$refs.map.updateDriveCar(this.currentGpsPosition.split(','));
              this.$refs.map.setFitView();
              resolve();
            })
            .catch(reason => {
              reject(reason);
            });
        }
      });
    },
    clearDrivePath() {
      if (this.hasDrivePath) {
        console.log('清理规划线路');
        if (this.$refs.map) {
          this.$refs.map.removePathNavigator();
          this.hasDrivePath = false;
        }
      }
    },
    onMessageArrive(message) {
      let str = message.payloadString;
      if (message.topic === this.getTaxiOrderTopic) {
        // 更新订单状态
        let result = JSON.parse(str);
        console.log('接收到MQTT系统消息：', result);
        if (this.$refs.bottom) {
          this.$refs.bottom.getTaxiOrder(result.orderId);
        }
      } else if (message.topic === this.getTaxiGpsTopic) {
        // 更新司机位置
        let jsonstr = decryptByDESModeEBC(str);
        let result = JSON.parse(jsonstr);
        console.log('接收到MQTT司机位置消息：', result);
        if (result.position) {
          let positionStr = decryptByDESModeEBC(result.position);
          this.$store.commit('setCurrentGpsPosition', positionStr);
        }
      }
    },
    goBack() {
      if (this.$refs.bottom) {
        this.$refs.bottom.goBack();
      }
    },
    onMqttLost(response) {
      console.error('MQTT连接丢失，这有可能是消息内部处理出错!');
    },
    doClear() {
      console.log('销毁出租车视图相关内容');
    }
  },
  beforeDestroy() {
    this.doClear();
  },
  watch: {
    getCurrentLocation(newVal) {
      if (this.getTaxiBottomType === '0') {
        this.$refs.map.initCenter(this.getCurrentLocation.coordinate);
      }
    },
    getTaxiBottomType(newVal) {
      if (newVal === '0') {
        // 选择起点终点状态
        if (this.$refs.map) {
          this.$refs.map.clearMap();
          this.$refs.map.initCenter();
          this.$refs.map.initPositionPicker();
        }
      } else if (newVal === '1') {
        // 确认呼叫出租车
        this.$refs.map.stopPositionPicker();
        if (this.$refs.map) {
          if (this.taxiStartPosition) {
            this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition);
          }
          this.$refs.map.stopPositionPicker();
        }
      } else if (newVal === '2') {
        this.$refs.map.stopPositionPicker();
        if (this.getTaxiOrderInfoData && this.getTaxiOrderInfoData.order_no !== '') {
          this.initMqtt();
        }
      } else if (newVal === '3') {
        this.$refs.map.stopPositionPicker();
        if (this.taxiStartPosition) {
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition, true);
        }
        this.clearDrivePath();
        this.$store.commit('closeMqtt');
        this.orderTopicSubscribed = false;
        this.gpsTopicSubscribed = false;
      }
    },
    currentGpsPosition(newVal) {
      console.log('司机位置更新 ：', newVal);
      if (this.$refs.map) {
        this.$refs.map.updateDriveCar(newVal.split(','));
      }
    },
    getTaxiStatus(newVal) {
      switch (newVal) {
        case TAXI_STATUS_ORDERING: {
          // 待抢单
          this.$refs.map.clearMap();
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition);
          this.$store.dispatch('getTaxiNearDrivers', this.taxiStartPosition.start_lnglat).then(() => {
            if (this.taxiNearDrivers.length > 0) {
              this.$refs.map.createTextTip(this.taxiStartPosition.start_lnglat.split(','), '正在为您预约出租车', '0');
            } else {
              this.$refs.map.createTextTip(this.taxiStartPosition.start_lnglat.split(','), '附近暂时没有出租车', '0');
            }
          });
          break;
        }
        case TAXI_STATUS_STANDBY: {
          // 待接驾
          this.$refs.map.clearMap();
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition);
          break;
        }
        case TAXI_STATUS_PICKING: {
          // 接驾中
          this.$refs.map.clearMap();
          this.$refs.map.addStartMarker(this.taxiStartPosition.start_lnglat.split(','), this.taxiStartPosition.start_pst);
          if (this.currentGpsPosition !== '') {
            this.$refs.map.updateDriveCar(this.currentGpsPosition.split(','));
            this.initDrivePath(this.currentGpsPosition.split(','), this.taxiStartPosition.start_lnglat.split(',')).then(() => {
              this.$refs.map.createTextTip(this.currentGpsPosition.split(','), '', '1');
            });
          }
          this.subscribeGpsTopic();
          this.$refs.map.setFitView();
          break;
        }
        case TAXI_STATUS_ARRIVED: {
          // 已到达
          this.$refs.map.clearMap();
          this.$refs.map.addStartMarker(this.taxiStartPosition.start_lnglat.split(','), this.taxiStartPosition.start_pst);
          this.clearDrivePath();
          if (this.currentGpsPosition !== '') {
            this.$refs.map.updateDriveCar(this.currentGpsPosition.split(','));
            this.$refs.map.createTextTip(this.currentGpsPosition.split(','), '司机已到达', '0');
          }
          this.subscribeGpsTopic();
          this.$refs.map.setFitView();
          break;
        }
        case TAXI_STATUS_TRAVELLING: {
          // 行程中
          this.$refs.map.clearMap();
          if (this.currentGpsPosition !== '') {
            this.$refs.map.addEndMarker(this.taxiEndPosition.end_lnglat.split(','), this.taxiEndPosition.end_pst);
            this.$refs.map.updateDriveCar(this.currentGpsPosition.split(','));
            this.initDrivePath(this.currentGpsPosition.split(','), this.taxiEndPosition.end_lnglat.split(',')).then(() => {
              this.$refs.map.createTextTip(this.currentGpsPosition.split(','), '', '2');
            });
          }
          this.subscribeGpsTopic();
          this.$refs.map.setFitView();
          break;
        }
        case TAXI_STATUS_FINISHED: {
          // 已完成
          this.$refs.map.clearMap();
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition, true, true);
          this.clearDrivePath();
          this.orderTopicSubscribed = false;
          this.gpsTopicSubscribed = false;
          this.$refs.map.setFitView();
          this.$store.commit('clearGpsPosition');
          break;
        }
        case TAXI_STATUS_CANCELD: {
          // 订单取消
          this.$refs.map.clearMap();
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition, true);
          this.clearDrivePath();
          this.$store.commit('closeMqtt');
          this.orderTopicSubscribed = false;
          this.gpsTopicSubscribed = false;
          this.$refs.map.setFitView();
          this.$store.commit('clearGpsPosition');
          break;
        }
        case TAXI_STATUS_CLOSED: {
          // 订单关闭
          this.$refs.map.clearMap();
          this.$refs.map.showStartEndPosition(this.taxiStartPosition, this.taxiEndPosition, true, true);
          this.clearDrivePath();
          this.$store.commit('closeMqtt');
          this.orderTopicSubscribed = false;
          this.gpsTopicSubscribed = false;
          this.$refs.map.setFitView();
          this.$store.commit('clearGpsPosition');
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'getCurrentLocation',
      'taxiStartPosition',
      'taxiEndPosition',
      'getTaxiBottomType',
      'getCallTaxiData',
      'getTaxiOrderInfoData',
      'getTaxiStatus',
      'mqttConfig',
      'mqttClient',
      'mqttConnected',
      'getTaxiOrderTopic',
      'getTaxiGpsTopic',
      'currentGpsPosition',
      'gpsStatus',
      'taxiNearDrivers'
    ])
  }
};
</script>

<style lang="stylus" scoped>
#taxi {
  .map {
    height: calc(100vh - 170px);
  }

  .map100 {
    height: 100vh;
  }
}
</style>
